package c11;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * 使用ThreadLocal的方式解决线程安全问题，稳得一笔
 */
public class TestSimpleDateFormat3 {
    //创建ThreadLocal实例
    private static ThreadLocal<DateFormat> safeSdf=new ThreadLocal<DateFormat>(){
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("2018-12-18 16:06:12");
        }
    };

    public static void main(String[] args) {
        for (int i = 0; i < 50; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        //使用单例日期解析文本
                        System.out.println(safeSdf.get().parse("2018-12-18 16:06:12"));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }finally {
                        //使用完记得清除，避免内存泄漏
                        safeSdf.remove();
                    }
                }
            });
            thread.start();
        }
    }
}
